<template>
  <div>
   取消请求
   <button @click="toGet">get请求</button> 
   <button @click="toPost">post请求</button>
   <button @click="toPut">put请求</button>
  </div>
</template>

<script>
export default {
   methods:{
      // 用CancelToken.source工厂方法创建 cancel token
      toGet(){
         var CancelToken = axios.CancelToken;  
         console.log(CancelToken);
         var sourse = CancelToken.sourse();  //sourse是创建出的cancel token
         axios.get("https://www.baidu.com", {
            CancelToken: sourse.token,//拿到唯一标识给请求
         }).catch((thrown)=>{
            if(axios.isCancel(thrown)){
               console.log("Request canceled", thrown.message);
            }
         })
         sourse.cancel("请求取消了")
      },
      toPost(){
         var CancelToken = axios.CancelToken;  
         var sourse = CancelToken.sourse();
         axios.post("https://www.baidu.com", {
            name:"Myname",
         },{
            CancelToken: sourse.token,
         }).catch((thrown)=>{
            if(axios.isCancel(thrown)){
               console.log("Request canceled", thrown.message);
            }
         })
         sourse.cancel("请求取消了")
      },
      
      // 通过传递一个 executor 函数到 CancelToken 的构造函数来创建 cancel token：
      toPut(){
         const CancelToken = axios.CancelToken;
         let cancel;
         axios.put("https://www.baidu.com", {
            cancelToken: new CancelToken(function executor(c) {
               cancel = c;
            })
         });
         cancel(); 
      }
   }
}
</script>

<style>

</style>